package com.hz.api.admin.web.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hz.api.admin.common.exception.BizException;
import com.hz.api.admin.model.dao.ApiUserArticleTagDao;
import com.hz.api.admin.model.dao.ApiUserArticlesDao;
import com.hz.api.admin.model.entity.ApiUserArticleTagEntity;
import com.hz.api.admin.model.entity.ApiUserArticlesEntity;
import com.hz.api.admin.model.enums.ArticleTags;
import com.hz.api.admin.model.request.SaveArticleRequest;
import com.hz.api.admin.model.vo.ArticleListVO;
import com.hz.api.admin.web.config.thread.UserContextHolder;
import com.hz.api.admin.web.service.ArticleService;
import com.hz.api.admin.web.service.sql.UserArticleTagService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ArticleServiceImpl implements ArticleService {

    @Resource
    private ApiUserArticlesDao apiUserArticlesDao;

    @Resource
    private UserArticleTagService userArticleTagService;

    @Override
    @Transactional(rollbackFor = {BizException.class, Exception.class})
    public void saveArticle(SaveArticleRequest request) {
        // 写入文章
        try {
            ApiUserArticlesEntity entity = new ApiUserArticlesEntity();
            entity.setArticleContent(request.getArticleContent());
            entity.setArticleIndex(request.getArticleIndex());
            entity.setArticlePost(0L);
            entity.setArticleZan(0L);
            entity.setArticleView(0L);
            entity.setArticleTitle(request.getArticleTitle());
            entity.setCreateTime(new Date());
            entity.setModifyTime(new Date());
            entity.setArticlePic("");
            apiUserArticlesDao.insert(entity);
            // 写入标签
            List<ApiUserArticleTagEntity> list = new ArrayList<>();
            for (Integer integer : request.getTag()) {
                ApiUserArticleTagEntity tag = new ApiUserArticleTagEntity();
                tag.setArticleId(entity.getId());
                tag.setTagValue(integer);
                tag.setTagName(ArticleTags.getNameById(integer));
                list.add(tag);
            }
            userArticleTagService.saveBatch(list);
        } catch (Exception e) {
            log.error("添加文章失败: {}", e);
        }

    }

    @Override
    public PageInfo<ArticleListVO> articleList(int pageSize, int pageNum, List<Integer> tags) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("create_time");
        // 取出符合条件的文章ID
        PageInfo<ArticleListVO> retPage = new PageInfo<>();
        if (CollectionUtils.isNotEmpty(tags)) {
            QueryWrapper queryWrapper1 = new QueryWrapper();
            queryWrapper1.in("tag_value", tags);
            List<ApiUserArticleTagEntity> entities = userArticleTagService.list(queryWrapper1);
            if (CollectionUtils.isEmpty(entities)) {
                return retPage;
            }
            List<Long> articleId = entities.stream().map(ApiUserArticleTagEntity::getArticleId).distinct().collect(Collectors.toList());
            queryWrapper.in("id", articleId);
        }

        PageInfo<ApiUserArticlesEntity> articlesEntities = PageHelper.startPage(pageNum, pageSize)
                .doSelectPageInfo(() -> apiUserArticlesDao.selectList(queryWrapper));
        List<ApiUserArticlesEntity> list = articlesEntities.getList();
        List<ApiUserArticleTagEntity> list1 = userArticleTagService.list();
        if (CollectionUtils.isEmpty(list)) {
            retPage.setList(null);
            return retPage;
        }
        Map<Long, Set<String>> tagMap = new HashMap<>();
        for (ApiUserArticleTagEntity tag : list1) {
            tagMap.computeIfAbsent(tag.getArticleId(), k -> new HashSet<>()).add(tag.getTagName());
        }
        List<ArticleListVO> retList = new ArrayList<>();
        for (ApiUserArticlesEntity article : list) {
            ArticleListVO articleListVO = new ArticleListVO();
            BeanUtils.copyProperties(article, articleListVO);
            articleListVO.setTags(tagMap.get(article.getId()));
            retList.add(articleListVO);
        }
        BeanUtils.copyProperties(articlesEntities, retPage);
        retPage.setList(retList);
        return retPage;
    }

    @Override
    public ArticleListVO getArticleDetail(Long articleId) {
        ApiUserArticlesEntity article = apiUserArticlesDao.selectById(articleId);
        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("article_id", articleId);
        List<ApiUserArticleTagEntity> tags = userArticleTagService.list(queryWrapper1);
        Set<String> tagNames = tags.stream().map(ApiUserArticleTagEntity::getTagName).collect(Collectors.toSet());
        ArticleListVO articleListVO = new ArticleListVO();
        BeanUtils.copyProperties(article, articleListVO);
        articleListVO.setTags(tagNames);
        return articleListVO;
    }
}
